package com.santoker.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.santoker.baseservice.ApiResponseCode;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;

public class FilterUtil {

    public static Mono<Void> customError(ServerWebExchange exchange, ApiResponseCode apiResponseCode) {
        return customError(exchange, apiResponseCode.getCode(), apiResponseCode.getMsg(), HttpStatus.OK);
    }

    public static Mono<Void> customError(ServerWebExchange exchange, ApiResponseCode apiResponseCode, HttpStatus httpStatus) {
        return customError(exchange, apiResponseCode.getCode(), apiResponseCode.getMsg(), httpStatus);
    }

    public static Mono<Void> customError(ServerWebExchange exchange, String code, String msg, HttpStatus httpStatus) {
        Map<String, Object> resultMap = new HashMap<>(2);
        resultMap.put("code", code);
        resultMap.put("msg", msg);
        return Mono.defer(() -> {
            byte[] bytes = new byte[0];
            try {
                bytes = new ObjectMapper().writeValueAsBytes(resultMap);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(httpStatus);
            response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Flux.just(buffer));
        });
    }


    /**
     * 删除请求路径服务名前缀
     *
     * @param exchange
     * @param chain
     * @return
     */
    public static Mono<Void> removePrefix(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        String rawPath = request.getURI().getRawPath();
        String newPath = "/" + Arrays.stream(StringUtils.tokenizeToStringArray(rawPath, "/"))
                .skip(1l).collect(Collectors.joining("/"));
        ServerHttpRequest newRequest = request.mutate()
                .path(newPath)
                .build();
        exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());

        return chain.filter(exchange.mutate()
                .request(newRequest).build());
    }


}
